var map;
var mgr;
var icons = {};
var allmarkers = [];
var count=0;


// send request via post
function RequestPost(function_name, opt_argv) 
{
  if (!opt_argv)
    opt_argv = new Array();
 
  // Find if the last arg is a callback function; save it
  var callback = null;
  var len = opt_argv.length;
  if (len > 0 && typeof opt_argv[len-1] == 'function') {
    callback = opt_argv[len-1];
    opt_argv.length--;
  }
  var async = (callback != null);
 
  // Build an Array of parameters, w/ function_name being the first parameter
  var params = new Array(function_name);
  for (var i = 0; i < opt_argv.length; i++) {
    params.push(opt_argv[i]);
  }
  var body = JSON.stringify(params);

  // Create an XMLHttpRequest 'POST' request w/ an optional callback handler 
  var req = new XMLHttpRequest();
  req.open('POST', '/rpc', async);
 
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  req.setRequestHeader("Content-length", body.length);
  req.setRequestHeader("Connection", "close");

  if (async) {
    req.onreadystatechange = function() {
      if(req.readyState == 4 && req.status == 200) {
        var response = null;
        try {
         response = JSON.parse(req.responseText);
        } catch (e) {
         response = req.responseText;
        }
        callback(response);
      }
    }
  }
 
  // Make the actual request
  req.send(body);
}

function changemapcentertolatlng(lat, lng)
{
  map.setCenter(new GLatLng(lat, lng), 14);
  return true;
}

function changemapcenterto(location)
{
  var loctolatlng = new Array();
  loctolatlng['nanshang'] = {'lat':22.532, 'lng':113.931}; // 22.53204,113.931656
  loctolatlng['futian'] = {'lat':22.548, 'lng':114.084};   // 22.548846,114.084778
  loctolatlng['luohu'] = {'lat':22.545, 'lng':114.140};    // 22.545675,114.140396
  loctolatlng['baoan'] = {'lat':22.553, 'lng':113.917};    // 22.553285,113.91758
  loctolatlng['longhua'] = {'lat':22.656, 'lng':114.026};   // 22.656293,114.026756
  loctolatlng['beijing'] = {'lat':39.916, 'lng':116.396};   // 39.916245,116.396885
  loctolatlng['shanghai'] = {'lat':31.227, 'lng':121.482};   // 31.227403,121.48269
      
  if ( loctolatlng[location] )
  {
    return changemapcentertolatlng(loctolatlng[location]['lat'], loctolatlng[location]['lng']);
  }
  
  return null;      
} 

function loadAddmap()
{
  
  //map.clearOverlays();  
  map.setCenter(new GLatLng(22.532, 113.931), 14);

  // Add the Terrain Map Type
  //map.setMapType(G_DEFAULT_MAP_TYPES);  
  //map.addMapType(G_PHYSICAL_MAP);
  //map.addMapType(G_HYBRID_MAP);

  // Add contorls
  var mapControl = new GMapTypeControl();
  map.addControl(mapControl);
  map.addControl(new GLargeMapControl());
  
  // Add overview
  overview = new GOverviewMapControl(new GSize(150, 150));
  map.addControl(overview, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT)); 	
	
  // 创建本地搜索控件并将其添加到地图
  var lsc = new google.maps.LocalSearch(); 
  map.addControl(new google.maps.LocalSearch());
}

/////////////////////////////
function addMarkers()
{
  
}

function createNewMarker(posn, title, icon) {
  var marker = new GMarker(posn, {title: title, icon: icon, draggable:true });
  GEvent.addListener(marker, 'dblclick', function() { mgr.removeMarker(marker) } ); 
  return marker;
}

function deleteMarker() {
  var markerNum = parseInt(document.getElementById("markerNum").value);
  mgr.removeMarker(allmarkers[markerNum]);
}

function clearMarkers() {
  mgr.clearMarkers();
}

function reloadMarkers() {
  setupOfficeMarkers();
}

function setupOfficeMarkers() 
{
  allmarkers.length = 0;
  for (var i in officeLayer) {
    var layer = officeLayer[i];
    var markers = [];
    for (var j in layer["places"]) {
      var place = layer["places"][j];
      var icon = getIcon(place["icon"]);
      var title = place["name"];
      var posn = new GLatLng(place["posn"][0], place["posn"][1]);
      var marker = createMarker(posn,title,icon); 
      markers.push(marker);
      allmarkers.push(marker);
    }
    mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
  }
  mgr.refresh();
}


////////////////////////////
function addListener()
{
  GEvent.addListener(map, "moveend", function() {
    var center = map.getCenter();
    document.getElementById("message").innerHTML = "当前地图中心为：" + center.toString();
  });

  GEvent.addListener(map,"click", function(overlay,point) {     
    var myHtml = _makePointHtml(point);
    count ++;
    var marker = new GMarker(point, {title: '第 '+count+' 个标记', draggable:true });
    GEvent.addListener(marker, 'dblclick', function() { marker.hide() } ); 
    GEvent.addListener(marker, "dragstart", function() {
        marker.closeInfoWindow();
    });
    GEvent.addListener(marker, "dragend", function() {
        var point = marker.getPoint();
        var myHtml = _makePointHtml(point);
        marker.openInfoWindowHtml(myHtml);
    });

    map.addOverlay(marker);
    map.openInfoWindow(point, myHtml);
  });
}

function _makePointHtml(point){
    var myHtml = "<p>经纬度:" + point.toUrlValue() + "</p>";
    myHtml += '<form action="/savepoint" method="get" target="_blank">';
    myHtml += '<input name="lat" type="hidden" value=' + point.lat() + ' />';
    myHtml += '<input name="lng" type="hidden" value=' + point.lng() + ' />';
    myHtml += '注释：<input name="comment" type="text" /><input type="submit" value="保存"/>';
    myHtml +='</form>';
    return myHtml;
}

